<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useTradingAccountStore } from '@/stores/stock'
import { ListTradingAccount, CreateTradingAccount } from '@/api/note'

const store = useTradingAccountStore()

const dialog = reactive({
  addTradingAccountForm: false,
})

// 页面初始化
onMounted(() => {
  console.log('trading account mounted')
  if (store.tradingAccountList.length === 0) {
    ListTradingAccount().then((response) => {
      if (response.code === 0) {
        let data = response.data
        store.setTradingAccountList(data)
        for (let i = 0; i < data.length; i++) {
          if (data[i].isDefault) {
            store.setCurrentTradingAccount(data[i].id, data[i].name, data[i].remark)
          }
        }
      }
    })
  }
})

// 账户管理
const switchTradingAccount = function (item) {
  store.setCurrentTradingAccount(item.id, item.name, item.remark)
}

const addTradingAccountForm = ref({
  name: '',
  remark: '',
})

const AddTradingAccount = function () {
  CreateTradingAccount(addTradingAccountForm.value.name, addTradingAccountForm.value.remark).then(
    (resp) => {
      if (resp.code === 0) {
        ElMessage.success(resp.msg)
        dialog.addTradingAccountForm = false

        ListTradingAccount().then((resp) => {
          if (resp.code === 0) {
            store.setTradingAccountList(resp.data)
          }
        })
      }
    },
  )
}
</script>

<template>
  <div>
    <el-dropdown @command="switchTradingAccount" trigger="click" split-button>
      <span>
        {{ store.currentTradingAccount.name }}
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-for="item in store.tradingAccountList" :key="item.id" :command="item"
            >{{ item.name }}
          </el-dropdown-item>
          <el-dropdown-item
            divided
            @click.prevent="dialog.addTradingAccountForm = true"
            command="__add"
            >添加
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!--    添加交易账户弹框   -->
    <el-dialog v-model="dialog.addTradingAccountForm" title="Add Trading Account" width="500">
      <el-form :model="addTradingAccountForm">
        <el-form-item label="Name" label-width="140px">
          <el-input v-model="addTradingAccountForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="Remark" label-width="140px">
          <el-input v-model="addTradingAccountForm.remark" autocomplete="off" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="AddTradingAccount">Create</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped></style>
